using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.Ewe_Files;
using MediatR;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.Ewe_Files
{
    /// <summary>
    /// 母羊档案创建命令处理器
    /// </summary>
    public class CreateEweFileCommandHandler : IRequestHandler<CreateEweFileCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<EweFile> _eweRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateEweFileCommandHandler> _logger;

        public CreateEweFileCommandHandler(
            IBaseRepository<EweFile> eweRepository,
            IMapper mapper,
            ILogger<CreateEweFileCommandHandler> logger)
        {
            _eweRepository = eweRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理母羊档案创建命令
        /// </summary>
        /// <param name="request">母羊档案创建命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public async Task<ApiResult<int>> Handle(CreateEweFileCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("母羊档案创建请求参数为空");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "请求参数不能为空", data = 0 };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"母羊档案创建数据验证失败: {errorMessage}");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = errorMessage, data = 0 };
                }

                // 创建实体
                var eweFile = new EweFile
                {
                    EarSignal = request.EarSignal,
                    Variety = request.Variety,
                    ElectronicEarTag = request.ElectronicEarTag,
                    GeneRank = request.GeneRank,
                    FatherNumber = request.FatherNumber,
                    MotherNumber = request.MotherNumber,
                    DateofBirth = request.DateofBirth,
                    EntryDate = request.EntryDate,
                    PlaceOfBirth = request.PlaceOfBirth,
                    BirthWeight = request.BirthWeight,
                    Note = request.Note,
                    IsDeleted = false
                };

                // 保存到数据库
                var result = await _eweRepository.AddAsync(eweFile);
                
                if (result > 0)
                {
                    _logger.LogInformation($"成功创建母羊档案，耳号: {request.EarSignal}");
                    return new ApiResult<int> { Code = ApiEnum.新增成功, Message = "母羊档案创建成功", data = result };
                }
                else
                {
                    _logger.LogError($"创建母羊档案失败，耳号: {request.EarSignal}");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "母羊档案创建失败", data = 0 };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<int> { Code = ApiEnum.新增失败, Message = ex.Message, data = 0 };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建母羊档案时发生系统异常: {ex.Message}");
                return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "系统异常，请联系管理员", data = 0 };
            }
        }
    }
}